package com.zhuiyun.project.api.collectVideo.controller;

import cn.hutool.json.JSONObject;
import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.collectVideo.model.FavoritesModel;
import com.zhuiyun.project.api.collectVideo.service.FavoritesService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.constants.CommonConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName FavoritesController
 * @Description TODO 收藏夹
 * @Author XC8
 * @Date 2024/3/4 9:41
 **/
@RestController
@RequestMapping("favoritesController")
@Api(tags = "收藏夹模块")
public class FavoritesController {
    @Autowired
    private FavoritesService favoritesService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/getFavoritesById")
    @ApiOperation(value = "根据id用户信息查询收藏夹")
    public CommonResult getFavoritesById(String token) throws CommonException {
        String jsonstr = stringRedisTemplate.opsForValue().get(token);
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.ok(null);
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            int userId = json0bject.getInt("id");
            return CommonResult.ok(favoritesService.getFavoritesById(userId));
        }


    }

    /**
    * @Author XC8
    * @Description 新增前端收藏夹
    * @Date 2024/3/4 14:59
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @PutMapping("addFavorite")
    @ApiOperation(value = "新增前端收藏夹")
    public CommonResult addFavorite(@RequestBody FavoritesModel favoritesModel)throws CommonException{
        String jsonstr = stringRedisTemplate.opsForValue().get(favoritesModel.getToken());
        if (jsonstr == null || jsonstr.equals("")) {
            return CommonResult.ok(null);
        } else {
            // 使用JSONObject解析ISON字符串
            JSONObject json0bject = new JSONObject(jsonstr);
            // 获取id字段的值
            int userId = json0bject.getInt("id");
            favoritesModel.setUserId(userId);
            return CommonResult.ok(favoritesService.addFavorite(favoritesModel));
        }

    }

    /**
    * @Author XC8
    * @Description 删除收藏夹
    * @Date 2024/3/4 20:05
    * @Return com.zhuiyun.project.common.response.CommonResult
    */
    @PostMapping("favoritesDelete")
    @OptLog(modular = "收藏夹",type = CommonConstants.DELETE,describe = "删除收藏夹")
    public CommonResult favoritesDelete(Integer fId){
        return favoritesService.favoritesDelete(fId);
    }



}
